import configs from "@/config/config.json"
import http from "./http.js"

let config = {}
if(process.env.NODE_ENV === 'production'){
	config = configs.production
} else {
	config = configs.development
}
const {server} = config
http.baseUrl = server.baseUrl;

let xph = {}

xph.login = function(username, password){
	return http.post('login', {
		username, password
	}).then((res) => {
		if(!!res.data.token){
			xph.setDefaultToken(res.data.token)
		}
		return res; 
	})
}

xph.getRealData = function(id){
	return http.get('data/'+id).then(res=>{
		return res.data
	})
}

xph.parseRealData = async function(devices){
	await devices.map(async device => {
		const real = await xph.getRealData(device.id);
		device.sensors.forEach(ele => {
			let data = real['e'+(ele.num+1)]
			if(!!data && data !== 0x7fff){
				ele.value = data * ele.prec;
			}
		})
		device.valves.forEach(ele => {
			const bits = parseInt(ele.num / 32);
			const num = ele.num % 32;
			const state = real['j'+(num + 1)];
			if(!!state){
				ele.state = (state & (1 << bits)) !== 0
			}
		})
	})
}

function parseSensor(eleNum, eleName, elements, exp){
	exp = !!exp;
	let sensor = []
	eleNum.forEach((ele, index) => {
		if(ele != 100){
			let name = '', unit = '', prec = 1, min = 0, max = 32726;
			let element = elements.find(element => element.index === ele);
			
			if (!!element){
				name = element.name
				unit = element.unit
				prec = parseFloat(element.prec)
				min = parseFloat(element.min)
				max = parseFloat(element.max)
			} else {
				name = ''
			}
			if(eleName[index] !== "-"){
				name = eleName[index]
			}
			sensor.push({
				num: exp ? index+16 : index,
				index: parseInt(ele),
				name,
				value: 0x7fff,
				unit,
				prec,
				min,
				max
			})
		}
	})
	return sensor
}

function parseRelay(relayNum, relayName, relays, exp){
	exp = !!exp;
	let jk = []
	relayNum.forEach((ele, index) => {
		if(ele != 0){
			let name = '', unit = '';
			let relay = relays.find(relay => relay.index == ele);
			
			if (!!relay){
				name = relay.name
				unit = relay.unit
			} else {
				name = ''
			}
			if(relayName[index] !== "-"){
				name = relayName[index]
			}
			jk.push({
				num: exp ? index+32 : index,
				index: parseInt(ele),
				name,
				state: false,
				loading: false,
				selected: false
			})
		}
	})
	return jk
}

xph.getDevicesInfo = function(username){
	const user = http.get('user/'+username);
	const element = http.get('element');
	const relay = http.get('relay');
	
	return Promise.all([user, element, relay]).then((res) => {
		let devices = res[0].data.devices
		let elements = res[1].data
		let relays = res[2].data
		
		let device = devices.map(device => {
			let sensor = [], relay = [];
			let eleName = device.eleName.split('/')
			let eleNum = device.eleNum.split('/')
			sensor = parseSensor(eleNum, eleName, elements)
			
			if(!!device.elementExtendNum){
				let elementExtendName = device.elementExtendName.split('/')
				let elementExtendNum = device.elementExtendNum.split('/')
				let tmp = parseSensor(elementExtendNum, elementExtendName, elements, true)
				sensor = sensor.concat(tmp)
			}
			
			let relayName = device.relayName.split('/')
			let relayNum = device.relayNum.split('/')
			relay = parseRelay(relayNum, relayName, relays)
			
			if(!!device.relayExtendNum){
				let relayExtendName = device.relayExtendName.split('/')
				let relayExtendNum = device.relayExtendNum.split('/')
				let tmp = parseRelay(relayExtendNum, relayExtendName, relays, true)
				relay = relay.concat(tmp);
			}
			return {
				id: device.facId,
				name: device.facName,
				remark: device.remark,
				address: device.address,
				interval: device.readInterval,
				sensors: sensor,
				valves: relay
			}
		})
		return device;
	})
}

xph.controlDeviceValve = function(id, num, state){
	return http.post('relay', {
		deviceId: id,
		relayNum: num,
		relayState: state?1:0
	}).then(res => {
		return res.data
	})
}

/**
 * @param {Number} userId 	//获取用户轮灌配置
 * @return {Promise(Object)}
 * 	示例:
 * [{"id":9,"createTime":"2021-09-10 10:03:33","updateTime":"2021-09-10 10:03:33","userId":2111,"name":"测试1组","description":"测试","mode":true,"startTime":"2019-11-12 00:00:00","stopTime":"2019-11-12 23:59:59","duration":20,"interval":21,"circulation":1,"weekday":"1/2/3/4/5","groups":[{"id":37,"createTime":"2021-09-10 09:59:34","updateTime":"2021-09-10 09:59:34","userId":2111,"name":"1号组","description":"测试","rotationRelays":null}]},{"id":10,"createTime":"2021-09-10 10:31:11","updateTime":"2021-09-10 10:31:11","userId":2111,"name":"灌区名称","description":"测试","mode":true,"startTime":"2019-11-12 00:00:00","stopTime":"2019-11-12 23:59:59","duration":1,"interval":2,"circulation":1,"weekday":"1","groups":[{"id":38,"createTime":"2021-09-10 10:29:49","updateTime":"2021-09-10 10:29:49","userId":2111,"name":"2号组","description":"测试2号","rotationRelays":null}]}]
 */
xph.getRotationConfig = function(userId){
	return http.get(`user/${userId}/rotationconfig`).then(res=>{
		return res.data
	})
}
/**
 * @param {String} name				//名称
 * @param {String} description		//描述
 * @param {Boolean} mode			//模式是否开启
 * @param {Number} duration			//灌溉时长
 * @param {Number} interval			//轮灌间隔
 * @param {Number} circulation		//循环次数
 * @param {String} startTime		//开始时间
 * @param {String} stopTime			//结束时间
 * @param {Number} userId			//用户id
 * @param {String} weekday			//启用时间	格式 "0/1/2/3/4/5/6" 0 表示周天
 * @return {Promise(Boolean)}
 */
xph.setRotationConfig = function(name, description, mode, duration, interval, circulation, startTime, stopTime, userId, weekday){
	return http.post('rotationconfig', {
		name,
		 description, 
		 mode, 
		 duration,
		 interval,
		 circulation,
		 startTime,
		 stopTime,
		 userId,
		 weekday
	}).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} configId		//组Id
 * @param {Object} config		//组信息 getRotationConfig 返回的内容
 * @return {Promise(Boolean)}
 */
xph.editRotationConfig = function(configId, config){
	return http.put('rotationconfig/'+configId, config).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} configId		//组id
 * @return {Promise(Boolean)}	//
 */
xph.deleteRotationConfig = function(configId){
	return http.delete('rotationconfig/'+configId).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} configId
 * @param {Number[]} groupIds
 * @return {Promise(Boolean)}
 */
xph.setRotationConfigGroup = function(configId, groupIds){
	return http.post('rotationconfiggroup', {
		configId, groupIds
	}).then(res=>{
		return res.data
	})
}






/**
 * @param {String} username //用户名
 * @return {Object} 
 * 		示例:
 * 	[{"id":37,"createTime":"2021-09-10 09:59:34","updateTime":"2021-09-10 09:59:34","userId":2111,"name":"1号组","description":"测试","rotationRelays":[{"id":604,"createTime":"2021-09-10 09:59:57","updateTime":"2021-09-10 09:59:57","groupId":37,"facId":16069132,"relay":1},{"id":605,"createTime":"2021-09-10 10:12:08","updateTime":"2021-09-10 10:12:08","groupId":37,"facId":16069132,"relay":2}]},{"id":38,"createTime":"2021-09-10 10:29:49","updateTime":"2021-09-10 10:29:49","userId":2111,"name":"2号组","description":"测试2号","rotationRelays":[{"id":606,"createTime":"2021-09-10 10:30:19","updateTime":"2021-09-10 10:30:19","groupId":38,"facId":16069132,"relay":0}]}]
 */
xph.getRotationGroup = function(username){
	return http.get(`user/${username}/rotationgroup`).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} userId		//继电器组 用户id
 * @param {String} name			//继电器组 名称
 * @param {String} description	//继电器组 描述
 * @return {Promise(Boolean)} 	//true 新建成功
 */
xph.setRotationGroup = function(userId, name, description){
	return http.post('rotationgroup', {
		userId, name, description
	}).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} groupId		//组Id
 * @param {Object} group		//组信息 getRotationGroup 返回的内容
 * @return {Promise(Boolean)}
 */
xph.editRotationGroup = function(groupId, group){
	return http.put('rotationgroup/'+groupId, group).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} groupId		//组id
 * @return {Promise(Boolean)}	//
 */
xph.deleteRotationGroup = function(groupId){
	return http.delete('rotationgroup/'+groupId).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} facId		//设备Id
 * @param {Number} groupId		//组Id
 * @param {Number} relay		//继电器编号 从0 开始
 * @return {Promise(Boolean)}
 */
xph.setRotationRelay = function(facId, groupId, relay){
	return http.post('rotationrelay', {
		facId, groupId, relay
	}).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} facId		//设备Id
 * @param {Number} groupId		//组Id
 * @param {Number} relay		//继电器编号 从0 开始
 * @return {Promise(Boolean)}
 */
xph.editRotationRelay = function(facId, groupId, relay){
	return http.put('rotationrelay', {
		facId, groupId, relay
	}).then(res=>{
		return res.data
	})
}
/**
 * @param {Number} rotationRelayId		//轮灌继电器id
 * @return {Promise(Boolean)}			//
 */
xph.deleteRotationRelay = function(rotationRelayId){
	return http.delete('rotationrelay/'+rotationRelayId).then(res=>{
		return res.data
	})
}



xph.setDefaultToken = function(token){
	http.defaultHeader = Object.assign(http.defaultHeader, {token})
}


export default xph